package com.boomsecret.juc.atomic;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author wangjinliang on 2019/1/17.
 */
public class AtomicReferenceDemo {
    public static void main(String[] args) {
        AtomicReference<AtomicReferenceUser> atomicReference = new AtomicReference<>();
        System.out.println(atomicReference.get());

        AtomicReferenceUser temp01 = new AtomicReferenceUser();
        atomicReference.lazySet(temp01);
        System.out.println(atomicReference.get());

        System.out.println("-----------");
        AtomicReferenceUser temp02 = new AtomicReferenceUser(1);
        System.out.println(atomicReference.compareAndSet(temp01, temp02));
        System.out.println(atomicReference.get());

        System.out.println("-----------");
        AtomicReferenceUser temp03 = new AtomicReferenceUser(2);
        System.out.println(atomicReference.compareAndSet(temp01, temp03));
        System.out.println(atomicReference.get());

        System.out.println("-----------");
        AtomicReferenceUser temp04 = new AtomicReferenceUser(4);
        System.out.println(atomicReference.getAndUpdate(o -> temp04));
        System.out.println(atomicReference.get());

        System.out.println("-----------");
        AtomicReferenceUser temp05 = new AtomicReferenceUser(5);
        System.out.println(atomicReference.getAndAccumulate(temp05, (origin, target) -> target));
        System.out.println(atomicReference.get());
    }

    public static class AtomicReferenceUser {
        int count;

        AtomicReferenceUser() {}

        AtomicReferenceUser(int count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "AtomicReferenceUser{" +
                    "count=" + count +
                    '}';
        }
    }
}
